﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace FederationMembershipDB
{
    public partial class frmPurchaseItems : Form
    {
        List<Membership> purchMemReg = new List<Membership>();
        List<Product> purchProdItem = new List<Product>();
        List<LineItem> _lineItems = new List<LineItem>();
        
        Form _parent;

        struct membershipType
        {
            string strType;
            double dblAmount;

            public string Type
            {
                get { return strType; }
                set { strType = value; }
            }

            public double Amount
            {
                get { return dblAmount; }
                set { dblAmount = value; }
            }
        }
        

        List<membershipType> memTypeList = new List<membershipType>();
        List<Product> prodList = new List<Product>();
        List<TrainingPass> trainList = new List<TrainingPass>();
        List<PassType> passTypeList = new List<PassType>();
       

        #region formEvents
        public frmPurchaseItems(List<LineItem> lineItems,Form frmParent)
        {
            InitializeComponent();
            _lineItems = lineItems; //assigns the passed in lineItem List to the local lineItems list
            pnlMembership.Hide();
            pnlProducts.Hide();
            pnlTrainingPass.Hide();
            ddlPurchaseType.SelectedIndex = 0;
            _parent = frmParent;           
           
        }
        private void frmPurchaseItems_Load(object sender, EventArgs e)
        {
            //is the Load Event for the PURCHASE ITEMS form

            //set up for the panel pnlMembership
            pnlMembershipSetup();

            //set up for the panel pnlPurchItems
            pnlProductSetup();

            //set up for the panel pnlTrainingPass
            pnlTrainingPassSetup();


        }
        private void ddlPurchaseType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (ddlPurchaseType.SelectedIndex)
            {
                case 0: //"Select ->" is selected - hide all panels
                    pnlMembership.Hide();
                    pnlProducts.Hide();
                    pnlTrainingPass.Hide();
                    break;
                case 1: //Membership/Registration Fee is selected - display the Membership panel, hide the others
                    pnlProducts.Hide();
                    pnlTrainingPass.Hide();
                    pnlMembership.Show();
                    //bring panel to front
                    pnlMembership.BringToFront();
                    //call the 'Value Changed' event on the form load, to fill in the expiry label
                    txtDatePaid_ValueChanged(sender, e);
                   
                    break;
                case 2: //Training Pass is selected - display the Training Pass panel, hide the others
                    pnlMembership.Hide();
                    pnlProducts.Hide();
                    pnlTrainingPass.Show();
                    //bring panel to front
                    pnlTrainingPass.BringToFront();
                    break;
                case 3: //Products is selected - display the Products panel, hide the others
                   
                    pnlMembership.Hide();
                    pnlProducts.Show();
                    pnlTrainingPass.Hide();
                    //bring panel to front
                    pnlProducts.BringToFront();
                    break;
                default:
                    break;
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void purchMemberIDSearch()
        {
            //lookup ALL memberIDs in the database except those already listed
            StringBuilder sbSQL = new StringBuilder("SELECT * FROM Member WHERE ID LIKE '%%'");

            if (lsvMembers.Items.Count > 0)
            {
                foreach (ListViewItem item in lsvMembers.Items)
                {
                    sbSQL.Append(" AND ID <> '" + item.SubItems[0].Text + "'"); //SubItems[0] is the ID column
                }
            }

            string sqlCountMembershipID = "SELECT COUNT(*) FROM Member WHERE ID LIKE '%%';";
            string sqlSelectMembershipID = sbSQL.ToString() + ";";

            string sqlConcat = sqlCountMembershipID + sqlSelectMembershipID;
            DataSet dsSearchMemberID = Utilities.SearchDatabase(sqlConcat);
            int count = int.Parse(dsSearchMemberID.Tables[0].Rows[0].ItemArray.GetValue(0).ToString());

            //if a member is found, add to the list view
            if (count >= 1)
            {//show Selectmember dialog as there is one or more members matching the search criteria

                Member _member = new Member();

                SelectMember frmSelectMember = new SelectMember(_member, dsSearchMemberID, "ID");//create a SelectMember form object, passing in the _member & dsSearchName variables
                //show the SelectMember form (as a Dialog form - can't click on other forms until this closed)
                frmSelectMember.ShowDialog();
                if (_member.ID == 0)
                {
                    return;
                }
                //create a list item to display in the list view "lsvPurchItems"
                ListViewItem newListTrainingPass = new ListViewItem(_member.ID.ToString());//the member id, into the MemberID column of the listview
                //add items to each column
                newListTrainingPass.SubItems.Add(_member.GivenName + " " + _member.LastName); //add the Members Name to the listview
                //add the list item to the list view
                lsvMembers.Items.Add(newListTrainingPass);
                //Reference: http://stackoverflow.com/questions/473148/c-sharp-listview-how-do-i-add-items-to-columns-2-3-and-4-etc

            }
            else//else popup error message (messagebox)
            {
                MessageBox.Show("Sorry, No members could not be found. Please try again", "Member not found", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        #endregion

        #region membershipPanel
        private void pnlMembershipSetup()
        {
            //called from frmPurchaseItems_Load()
            //when the Membership Panel is loaded, do:
            //    - set the membership number label to the number from the parent form
            //    - fill the Membership type drop down list

            //get the membership number from the parent form - set in frmPurchaseItems
            string strMemNum = ((TextBox)_parent.Controls["tabControl1"].Controls[3].Controls[0].Controls[0].Controls["txtPurchMemberID"]).Text;
            lblNewMemberNum.Text = strMemNum;
            
            //fill the drop down list for Academy Name
            
            Utilities.FillDropDownList("SELECT * FROM Academy_Lookup;", ddlAffiliatedAcademy, 1);

            //fill the drop down list for Membership Types
            fillMembershipTypeList();

        }       
        private void fillMembershipTypeList()
        {
            //called from pnlMembershipSetup()
            //loads the drop down list for Membership Types
            //fills the Membership Type structure

            //get the Membership types from the database: {Senior | Junior | Mighty Mites }
            string strSelect = "SELECT * FROM MembershipType_Lookup;";
            DataSet results = Utilities.SearchDatabase(strSelect);

            //loop through each row, to fill the memType stucture, and fill items in the mem type ddl
            foreach (DataRow myRow in results.Tables[0].Rows)
            {
                //fill the membershipType structure
                membershipType memItem = new membershipType();
                memItem.Amount = double.Parse(myRow["Fee"].ToString());
                memItem.Type = myRow["Type"].ToString();
                //add to the List memType
                memTypeList.Add(memItem);

                // Add each "Type" to the drop down list             
                ddlMembershipType.Items.Add(myRow["Type"].ToString());
            }

            ddlMembershipType.SelectedIndex = 0;
        }
        private void btnMembershipBack_Click(object sender, EventArgs e)
        {
            clearMembershipPanel();
            pnlMembership.Hide();
            ddlPurchaseType.SelectedIndex = 0;
        }
        private void clearMembershipPanel()
        {
            //Resets the fields in the membership panel
            txtRegAmountPaid.Text = "";
            txtDatePaid.Text = "";
            chkQuestionCompleted.Checked = false;
            chkContractCompleted.Checked = false;
            lblExpiryDate.Text = "";
            ddlAffiliatedAcademy.SelectedIndex = 0;
            ddlMembershipType.SelectedIndex = 0;
        }
        private bool validMembership()
        {
            bool isValid = false;
            int errorCount = 0;
            string strErrors = "Please review the following field(s):\r\n\r\n";
            
            if (ddlAffiliatedAcademy.SelectedItem.ToString().Contains("Select"))
            {
                strErrors += "Please select the Affiliated Academy.\r\n";
                errorCount++;
            }

            if (ddlMembershipType.SelectedItem.ToString().Contains("Select"))
            {
                strErrors += "Please select the Membership Type.\r\n";
                errorCount++;
            }

            double intRegFee = 0;
            try
            {
                intRegFee = double.Parse(txtRegAmountPaid.Text);
            }
            catch (Exception)
            {
                strErrors += "The Amount to be Paid needs to be numberic only.\r\n";
            }

            if (txtRegAmountPaid.Text == "" || intRegFee < 1)
            {
                strErrors += "Please enter the Amount to be Paid.\r\n";
                errorCount++;
            }

           
            if (errorCount > 0) //i.e. there are some fileds missing data
            {
                MessageBox.Show(strErrors, "Required Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                isValid = false;
            }
            else
            {
                isValid = true;
            }

            return isValid;
        }
        private void btnMembershipAdd_Click(object sender, EventArgs e)
        {
            //ensure required fields are filled in.
            if (!validMembership())
                return;


            //Add details into a variable, which passes back to the main form, when purchasing completed add to database table Registration Fee
            Membership purch = new Membership();
            fillPurchaseMembership(purch);

            //Add to the lineItems list that captures all Purchase types
            LineItem LI = new LineItem();
            LI.Type = "Membership"; //this is a membership registration type of product to purchase
            LI.Item = purch;
            //add to the Line Items list, to capture this and all items to be purchased.
            _lineItems.Add(LI);

            string strQ = "Do you want to add another item?";
            string strTitle = "Add another item?";
            //Referenece: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox.aspx retrieved: 21/09/2012
            var result = MessageBox.Show(this, strQ, strTitle, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

            switch (result)
            {
                case DialogResult.Cancel:
                    //do nothing so the user can edit the current item
                    break;
                case DialogResult.No: //returns to the Main form > Purchasing tab
                    //returns _lineItems list to main form as _lineItems is a reference to the main forms line items object - see constructor frmPurchaseItems()
                    DialogResult = System.Windows.Forms.DialogResult.Cancel;
                    break;
                case DialogResult.Yes: //form cleared to accept another item.
                    //re-setup the form 
                    clearMembershipPanel();
                    clearProductPanel();
                    clearTrainingPassPanel();
                    pnlMembership.Hide();
                    pnlProducts.Hide();
                    ddlPurchaseType.SelectedIndex = 0;
                    ddlMembershipType.SelectedIndex = 0;
                    break;
                default:
                    break;
            }

        }
        private void fillPurchaseMembership(Membership p)
        {
            //create and fill Membership/Registration data, based on the pnlMembership data fields            
            p.Payee = txtPayeeName.Text;
            p.RegistrationFee = new RegistrationFee(double.Parse(txtRegAmountPaid.Text),DateTime.Parse(txtDatePaid.Text),chkQuestionCompleted.Checked,chkContractCompleted.Checked);
            p.MembershipType = ddlMembershipType.SelectedItem.ToString();
            p.AffiliatedAcademy = new Academy(ddlAffiliatedAcademy.SelectedItem.ToString());
            p.CommencementDate = DateTime.Parse(txtDatePaid.Text);
            p.MembershipStatus = new MembershipStatus("Active"); //could be something like Active, suspended, expired etc
            p.MembershipExpiry = DateTime.Parse(lblExpiryDate.Text);

            //add to the Purchase Membership list, to capture the case where more than one membership is purchased.
            purchMemReg.Add(p);

        }
        private void txtDatePaid_ValueChanged(object sender, EventArgs e)
        {
            //Expiry date is +1 year from date paid.
            DateTime dt;
            if (DateTime.TryParse(txtDatePaid.Text, out dt))
            {
                lblExpiryDate.Text = dt.AddYears(1).ToShortDateString();
            }
            else
            {
                lblExpiryDate.Text = "";
            }
            
        }
        private void ddlMembershipType_SelectedIndexChanged(object sender, EventArgs e)
        {
            //based on the item selected, lookup the amount for that item (in the memType structure), and fill in the Amount Paid txtbox
            txtRegAmountPaid.Text = "";

            foreach (membershipType item in memTypeList)
            {
                if (ddlMembershipType.Text.ToUpper() == item.Type.ToString().ToUpper())
                {
                    txtRegAmountPaid.Text = item.Amount.ToString();
                    return; //break the for each as we have found the value we need
                }
            }
        }

        #endregion

        #region productsPanel
        private void pnlProductSetup()
        {
            //called from frmPurchaseItems_Load()
            //when the Product Panel is loaded, do:
            //    - fill the Membership type drop down list

            //fill the drop down list for Membership Types
            fillProductList();
            //select the 'Select ->' as the first item of ddlQty
            ddlQty.SelectedIndex = 0;

        }
        private void fillProductList()
        {
            //called from pnlProductSetup()
            //loads the drop down list for Products
            //fills the Products class

           
            //get the Products from the database e.g. Powerade, boxing hand wraps, protein powder etc
            string strSelect = "SELECT * FROM Product;";
            DataSet results = Utilities.SearchDatabase(strSelect);

            //loop through each row, to fill the memType stucture, and fill items in the mem type ddl
            foreach (DataRow myRow in results.Tables[0].Rows)
            {               
                //create and fill the product object
                Product prod = new Product();
                prod.ProductNumber = int.Parse(myRow["ID"].ToString());
                prod.ProductName = myRow["Name"].ToString();
                prod.PriceExGST = double.Parse(myRow["PriceExGST"].ToString());
                //prod.Quantity = int.Parse(ddlQty.SelectedText);
                
                //add to the List prodList
                prodList.Add(prod);

                // Add each "Product" to the drop down list             
                ddlProductList.Items.Add(prod.ProductName);
                
            }
            ddlProductList.Items.Insert(0, "Select ->");
            ddlProductList.SelectedIndex = 0;
        }
        private void btnProdBack_Click(object sender, EventArgs e)
        {
            clearProductPanel();
            pnlProducts.Hide();
            ddlPurchaseType.SelectedIndex = 0;
        }
        private void clearProductPanel()
        {
            //Resets the fields in the products panel
            ddlProductList.SelectedIndex = 0;
            ddlQty.SelectedIndex = 0;
            txtProdAmount.Text = "";
        }
        private void ddlProductList_SelectedIndexChanged(object sender, EventArgs e)
        {
            //based on the item selected, lookup the amount for that item (in the product class), and fill in the Amount Paid txtbox
            txtProdAmount.Text = "";

            foreach (Product item in prodList)
            {
                if (ddlProductList.Text.ToUpper() == item.ProductName.ToString().ToUpper())
                {
                    //set the lable next to the product ddl to show the exgstprice
                    lblPrice.Text = "ea. $ " + item.PriceExGST + " ex GST";
                    double dAmount = 0;
                    dAmount = item.PriceExGST * double.Parse(ddlQty.SelectedItem.ToString());
                    txtProdAmount.Text = dAmount.ToString();
                    return; //break the for each as we have found the value we need
                }
                else
                {
                    //this covers the 'Select ->' option of the drop down list
                    lblPrice.Text = "";
                }
            }
        }
        private void ddlQty_SelectedIndexChanged(object sender, EventArgs e)
        {
            //loop through each item in the global prodList, to match the selected item in the ddlProductlist to the global prodList to get the Amount
            //this will then be multiplied by the ddlQty value to get the Amount set.
            foreach (Product item in prodList)
            {
                if (ddlProductList.Text.ToUpper() == item.ProductName.ToString().ToUpper())
                {
                    double dAmount = 0;
                    dAmount = item.PriceExGST * double.Parse(ddlQty.SelectedItem.ToString());
                    txtProdAmount.Text = dAmount.ToString();
                    return; //break the for each as we have found the value we need
                }
            }
        }
        private bool validProduct()
        {
            bool isValid = false;
            int errorCount = 0;
            string strErrors = "Please review the following field(s):\r\n\r\n";

            if (ddlProductList.SelectedItem.ToString().Contains("Select"))
            {
                strErrors += "Please select the Product.\r\n";
                errorCount++;
            }

            
            double intProductFee = 0;
            try
            {
                intProductFee = double.Parse(txtProdAmount.Text);
            }
            catch (Exception)
            {
                strErrors += "The Amount needs to be numberic only.\r\n";
            }

            if (intProductFee < 1)
            {
                strErrors += "Please enter the Amount to be Paid.\r\n";
                errorCount++;
            }


            if (errorCount > 0) //i.e. there are some fileds missing data
            {
                MessageBox.Show(strErrors, "Required Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                isValid = false;
            }
            else
            {
                isValid = true;
            }

            return isValid;
        }
        
        private void btnProdAdd_Click(object sender, EventArgs e)
        {

            if (!validProduct())
                return;

            //Add details into a variable, which passes back to the main form, when purchasing completed add to database table Registration Fee
            Product purch = new Product();
            fillPurchaseProduct(purch);

            //Add to the lineItems list that captures all Purchase types
            LineItem LI = new LineItem();
            LI.Type = "Product"; //this is a membership registration type of product to purchase
            LI.Item = purch;
            //add to the Line Items list, to capture this and all items to be purchased.
            _lineItems.Add(LI);

            string strQ = "Do you want to add another item?";
            string strTitle = "Add another item?";
            //Referenece: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox.aspx retrieved: 21/09/2012
            var result = MessageBox.Show(this, strQ, strTitle, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

            switch (result)
            {
                case DialogResult.Cancel:
                    //do nothing so the user can edit the current item
                    break;
                case DialogResult.No: //returns to the Main form > Purchasing tab
                    //returns _lineItems list to main form as _lineItems is a reference to the main forms line items object - see constructor frmPurchaseItems()
                    DialogResult = System.Windows.Forms.DialogResult.Cancel;
                    break;
                case DialogResult.Yes: //form cleared to accept another item.
                    //re-setup the form 
                    clearMembershipPanel();
                    clearProductPanel();
                    clearTrainingPassPanel();
                    pnlMembership.Hide();
                    pnlProducts.Hide();
                    ddlPurchaseType.SelectedIndex = 0;
                    ddlMembershipType.SelectedIndex = 0;
                    break;
                default:
                    break;
            }
        }

        private void fillPurchaseProduct(Product p)
        {
            //create and fill Product item data, based on the pnlProducts data fields
            p.ProductName = ddlProductList.SelectedItem.ToString();
            p.PriceExGST = double.Parse(txtProdAmount.Text);
            p.Quantity = int.Parse(ddlQty.SelectedItem.ToString());

            //add to the Purchase Product list, to capture the case where more than one product type is purchased.
            purchProdItem.Add(p);
        }



        #endregion

        #region trainingPassPanel
        private void pnlTrainingPassSetup()
        {
            //Load the member Name from Form1 (Member Lookup) into: PayeeName & lsvMember
            //called from frmPurchaseItems_Load()
            //when the Training Pass Panel is loaded, do:
            //    - set the Payee name textbox to the name from the parent form
            //    - Add the memID and MemName to the listbox, as a default entry
            //    - fill the Pass type and Issued By drop down lists

            //get the membership number from the parent form - set in frmPurchaseItems
            string strMemID = ((TextBox)_parent.Controls["tabControl1"].Controls[3].Controls[0].Controls[0].Controls["txtPurchMemberID"]).Text;
            string strMemName = ((TextBox)_parent.Controls["tabControl1"].Controls[3].Controls[0].Controls[0].Controls["txtPurchMemberName"]).Text;
            ListViewItem _lviMem = new ListViewItem(strMemID);
            _lviMem.SubItems.Add(strMemName);

            //add the Default Member to the lsit view box
            lsvMembers.Items.Add(_lviMem);

            //add the Default member as the payee
            txtPayeeName.Text = strMemName;

            //fill the drop down list for Training Pass Types and Issued By (staff member name)            
            Utilities.FillDropDownList("SELECT * FROM StaffMember_Lookup;", ddlIssuedBy, 1);
            fillTrainingList();
            
            //TODO: Auto select Issued By based on the logged in Staff member
        }
        private void fillTrainingList()
        {
            //called from pnlProductSetup()
            //loads the drop down list for Products
            //fills the Products class
            
            //get the Products from the database e.g. Powerade, boxing hand wraps, protein powder etc
            string strSelect = "SELECT * FROM PassType_Lookup;";
            DataSet results = Utilities.SearchDatabase(strSelect);

            //loop through each row, to fill the fill items in the training pass type ddl
            foreach (DataRow myRow in results.Tables[0].Rows)
            {
                //create and fill the training Pass object
                PassType passType = new PassType(); //used in filling the Training Pass drop down list and
                passType.PassTypeName = myRow[1].ToString();
                passType.Fee = double.Parse(myRow[2].ToString());
                passType.NumberClasses = int.Parse(myRow[3].ToString());

                //add to the List prodList
                passTypeList.Add(passType); //each item will be off-set by 1 (the ddl has 'Select') from the index as the drop down list items - which will be used to auto fill the Fee text box and Number of Classes.
                
                // Add each "Product" to the drop down list             
                ddlPassType.Items.Add(passType.PassTypeName);

            }
            ddlPassType.Items.Insert(0, "Select ->");
            ddlPassType.SelectedIndex = 0;
        }
        private bool validTrainingPass()
        {
            bool isValid = false;
            int errorCount = 0;
            string strErrors = "Please review the following field(s):\r\n\r\n";

            if (txtPayeeName.Text == "")
            {
                strErrors += "Please enter the Payee of the Training Pass.\r\n";
                errorCount++;
            }
            if (ddlPassType.SelectedItem.ToString().Contains("Select"))
            {
                strErrors += "Please select the Type of Training Pass.\r\n";
                errorCount++;
            }
           
            double intFeeAmount = 0;
            try
            {
                intFeeAmount = double.Parse(txtFee.Text);
            }
            catch (Exception)
            {
                strErrors += "The Amount to be Paid needs to be numberic only.\r\n";
            }

            if (intFeeAmount < 1)
            {
                strErrors += "Please enter the Amount to be Paid.\r\n";
                errorCount++;
            }
            if (ddlIssuedBy.SelectedItem.ToString().Contains("Select"))
            {
                strErrors += "Please select the Staff Member that has Issued this Training Pass.\r\n";
                errorCount++;
            }

            int intNumClasses = 0;
            try
            {
                intNumClasses = int.Parse(txtNumClasses.Text);
            }
            catch (Exception)
            {
                strErrors += "The Number of classes needs to be a numberic value.\r\n";
            }

            if (intNumClasses < 1)
            {
                strErrors += "Please enter the Number of Classes for this Training Pass.\r\n";
                errorCount++;
            }

            if (lsvMembers.Items.Count < 1)
            {
                strErrors += "At least one Member needs to be on the Training Pass.\r\n";
                errorCount++;
            }

            if (errorCount > 0) //i.e. there are some fileds missing data
            {
                MessageBox.Show(strErrors, "Required Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                isValid = false;
            }
            else
            {
                isValid = true;
            }

            return isValid;
        }
        private void btnTrainPassAdd_Click(object sender, EventArgs e)
        {
            if (!validTrainingPass())
                return;


            //Add details into a variable, which passes back to the main form, when purchasing completed add to database table Registration Fee
            TrainingPass tPass = new TrainingPass();
            fillPurchaseTrainingPass(tPass);

            //Add to the lineItems list that captures all Purchase types
            LineItem LI = new LineItem();
            LI.Type = "TrainingPass"; //this is a training Pass type of product to purchase
            LI.Item = tPass;
            //add to the Line Items list, to capture this and all items to be purchased.
            _lineItems.Add(LI);

            string strQ = "Do you want to add another item?";
            string strTitle = "Add another item?";
            //Referenece: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox.aspx retrieved: 21/09/2012
            var result = MessageBox.Show(this, strQ, strTitle, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

            switch (result)
            {
                case DialogResult.Cancel:
                    //do nothing so the user can edit the current item
                    break;
                case DialogResult.No: //returns to the Main form > Purchasing tab
                    //returns _lineItems list to main form as _lineItems is a reference to the main forms line items object - see constructor frmPurchaseItems()
                    DialogResult = System.Windows.Forms.DialogResult.Cancel;
                    break;
                case DialogResult.Yes: //form cleared to accept another item.
                    //re-setup the form 
                    clearMembershipPanel();
                    clearProductPanel();
                    clearTrainingPassPanel();
                    pnlMembership.Hide();
                    pnlProducts.Hide();
                    ddlPurchaseType.SelectedIndex = 0;
                    ddlMembershipType.SelectedIndex = 0;
                    break;
                default:
                    break;
            }
        }
        private void fillPurchaseTrainingPass(TrainingPass p)
        {
            //create and fill Membership/Registration data, based on the pnlMembership data fields            
            p.PayeeName = txtPayeeName.Text;
            p.TrainingPassType = passTypeList[ddlPassType.SelectedIndex -1];
            p.IssueDate = DateTime.Today;
            p.FeePaid = Double.Parse(txtFee.Text);
            p.IssuedBy = ddlIssuedBy.SelectedText;
            p.NumberOfClassesRemaining = int.Parse(txtNumClasses.Text);

           
            foreach (ListViewItem item in lsvMembers.Items)
            {
                Member mem = new Member();
                mem.ID = int.Parse(item.SubItems[0].Text.ToString());
                mem.GivenName = item.SubItems[1].Text.ToString().Split(new char[] { ' ' }).First();
                mem.LastName = item.SubItems[1].Text.ToString().Split(new char[] { ' ' }).Last();

                p.AddMembers(mem);
            }
            
            //add to the Purchase Training Pass list, to capture the case where more than one training pass is purchased.
            trainList.Add(p);

        }
        private void btnTrainingPassBack_Click(object sender, EventArgs e)
        {
            clearTrainingPassPanel();
            pnlTrainingPass.Hide();
            ddlPurchaseType.SelectedIndex = 0;
        }
        private void clearTrainingPassPanel()
        {
            //Clear contents of controls on the traning pass panel
            txtPayeeName.Text = "";
            ddlPassType.SelectedIndex = -1;
            txtFee.Text = "";
            ddlIssuedBy.SelectedIndex = -1;
            txtNumClasses.Text = "";
            lsvMembers.Items.Clear();
        }
        private void btnLookup_Click(object sender, EventArgs e)
        {
            //lookup other members in the database, and if required, add them to the Training pass
            purchMemberIDSearch();
        }

        
        private void btnRemoveSelected_Click(object sender, EventArgs e)
        {
            //test that an item has been selected
            if (lsvMembers.SelectedIndices.Count == 0)
            {
                //message box that an item needs to be selcted.
                MessageBox.Show("Please select the required Member to be removed.", "Delete Item", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                //exit the function
                return;
            }
            //remove the selected item from the list box
            int index;
            foreach (ListViewItem item in lsvMembers.Items)
            {
                //only one item can be selected, as set by the properties of the listview box
                if (item.Selected)
                {
                    //set the index variable to use to remove the item from the list
                    index = item.Index;
                    try
                    {
                        //prompt for confirmation of Delete
                        DialogResult result = MessageBox.Show(this, "Are you sure you want to remove: " + item.SubItems[1].Text + "?", "Remove Item", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (result == DialogResult.Yes)
                        {
                            //remove the select item from the listview box
                            lsvMembers.Items.RemoveAt(index);
                            //remove the selected item from the _item list - should be the same index as the selected item in the listbox
                           // _lineItems.RemoveAt(index);
                            //only one item can be selected, so we don't need to test for any more selected items return out of this function - (developers decision, for simplicity)
                            return;
                        }

                    }
                    catch (Exception)
                    {
                        //message box that an error has occurred
                        MessageBox.Show("An error has occurred, please try again.", "Delete Item", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        //exit the function
                        return;
                    }
                }
            }
        }
        private void ddlPassType_SelectedIndexChanged(object sender, EventArgs e)
        {
            //based on the selection auto fill in the Fee txt box and the Number of Classes text box
            foreach (PassType item in passTypeList)
            {
                if(ddlPassType.SelectedItem != null)
                {
                    if (item.PassTypeName == ddlPassType.SelectedItem.ToString())
                    {
                        txtFee.Text = item.Fee.ToString();
                        txtNumClasses.Text = item.NumberClasses.ToString();

                        //only one item can be selected, exit function
                        return;
                    }
                }
            }
        }

        #endregion

        
        

       

    }
}
